const {
	loginCheck
} = require("../controller/user.js");

const {
	SuccModel,
	ErrModel
} = require("../model/resModel.js");

// cookie有效时间
const cooikeDate = () => {
  let d = new Date();
	d.setTime(d.getTime()+(24*60*60*1000));
	return d.toGMTString();
};
 

const userRouter = (req, res) => {
	const method = req.method;
	if (method === "POST" && req.path === "/api/user/login") {
		const {
			name,
			pw
		} = req.body;
		const result = loginCheck(name, pw);
		return result.then(e => {
			if (e) {
				// // 操作cookie
				// res.setHeader('Set-Cookie', `username=${e.username};path=/;httpOnly;Expires=${cooikeDate()}`)
				req.session.username = e.username;
				req.session.realname = e.realname;
				console.log('req.session is ' , req.session);
				return new SuccModel(e);
			}
			req.session.username = "";
			req.session.realname = "";
			return new ErrModel('登陆失败');
		});
		// return result.then(e=>{
		// 	if(e){
		// 		console.log('登录成功');
		// 		return new SuccModel(e)
		// 	}else{
		// 		console.log('登陆失败');
		// 		return new ErrModel('登陆失败')
		// 	}
		// })

	}
	// // 登陆验证测试
	// if (method === "GET" && req.path === '/api/user/login-test') {
 // 		if (req.session.username) {
	// 		return Promise.resolve(new SuccModel({
	// 			session: req.session
	// 		}))
	// 	}
	// 	return Promise.resolve(new ErrModel('没有登录'))
	// }
};

module.exports = userRouter;
